package com.itheima.controller;

import com.itheima.pojo.Emp;
import com.itheima.pojo.LoginRequest;
import com.itheima.pojo.LoginResult;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import com.itheima.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class LoginController {

    @Autowired
    private EmpService empService;

    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest loginRequest) {
        log.info("员工登录：{}", loginRequest);

        // 调用service进行登录验证
        Emp emp = empService.login(loginRequest);

        // 登录成功，生成JWT令牌
        if (emp != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", emp.getId());
            claims.put("username", emp.getUsername());

            String token = JwtUtils.generateJwt(claims);

            // 构造返回结果
            LoginResult loginResult = new LoginResult();
            loginResult.setId(emp.getId());
            loginResult.setUsername(emp.getUsername());
            loginResult.setName(emp.getName());
            loginResult.setToken(token);

            return Result.success(loginResult);
        }

        // 登录失败
        return Result.error("用户名或密码错误");
    }
}
